import { useState, useEffect, useRef, RefObject } from 'react';
import { VideoCourtSchema } from '@src/components/schema/videoCourt'
import style from './index.module.less'
import { Form, Row, Col, Button, Table, message, Space, DatePicker, FormInstance, TablePaginationConfig, Input } from 'antd';
import moment, { Moment } from 'moment'
import { getListRequest, delRequest, getResourceRequest, ResourceSchema } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { ColumnType } from 'antd/lib/table';
import { confirmAction } from '@js/tool'
import DetailModal from './components/detialModal'

const { Item } = Form
const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns (refreshFn: () => void, setVideoList: (v: string[]) => void, setVisible: (v: boolean) => void): Array<ColumnType<VideoCourtSchema>> {
  const list: Array<ColumnType<VideoCourtSchema>> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'subject',
      key: 'subject',
      width: 250,
      render: (v, l) => {
        return (
          <span>
            <span>{v}</span>
            {l.isMeetingExist === 0 && <span className={style.red}>（会议已删除）</span>}
          </span>
        )
      }
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150
    },
    {
      title: '时长（秒）',
      dataIndex: 'rcdTime',
      key: 'rcdTime',
      width: 120,
      render: (v) => {
        if (!v) {
          return 0
        }
        const s: string[] = []
        if (v > 3600) {
          s.push(`${Math.floor(v / 3600)}小时`)
          v = v % 3600
        }
        if (v > 60) {
          s.push(`${Math.floor(v / 60)}分`)
          v = v % 60
        }
        if (v > 0) {
          s.push(`${Math.floor(v)}秒`)
        }
        return s.join('')
      }
    },
    {
      title: '容量（MB）',
      dataIndex: 'rcdSize',
      key: 'rcdSize',
      width: 120
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 120,
      render: (value: string, line: VideoCourtSchema) => {
        return (
          <Space className={style['operate-cell']}>
            <a onClick={() => { setVideoList(line.url || []); setVisible(true) }}>详情</a>
            <a onClick={() => confirmAction(`您确定要删除 ${line.subject} 吗？删除后视频将无法恢复，请确认秘书已下载并保存该视频记录！`, () => { delHandle(line, refreshFn)})}>删除</a>
          </Space>
        )
      }
    }
  ]
  return list
}

async function delHandle (line: VideoCourtSchema, refreshFn: () => void) {
  const hide = message.loading('取消中')
  console.log(line, line.confUUID)
  const [e] = await awaitWrap(delRequest(line.confUUID))
  hide()
  if (e === null) {
    message.success('取消成功')
    refreshFn()
  }
}

function formatData (o: { [k: string]: any }): {[k: string]: any} {
  const d = {...o}
  if (d.start_date instanceof moment) {
    d.start_date = Math.floor((d.start_date as Moment).valueOf())
  }
  if (d.end_date instanceof moment) {
    d.end_date = Math.floor((d.end_date as Moment).valueOf())
  }
  return d
}

async function getTableData (
  o: { [k: string]: any } | null,
  formRef: RefObject<FormInstance>,
  current: number,
  pageSize: number,
  setLoading: (v: boolean) => void,
  setList: (v: VideoCourtSchema[]) => void,
  setTotal: (v: number) => void
) {
  const form = o || formRef.current?.getFieldsValue()
  const formData = formatData(form)

  const data = {
    page: current,
    limit: pageSize,
    ...formData
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(data))
  setLoading(false)
  if (e === null && d !== null) {
    d.list.forEach((li, i) => {
      li.index = ((current as number) - 1) * (pageSize as number) + i + 1
    })
    setList(d.list)
    setTotal(d.total)
  }
}

// 重置表格
function resetHandle (
  formRef: RefObject<FormInstance>,
  current: number,
  pageSize: number,
  setCurrent: (v: number) => void,
  setLoading: (v: boolean) => void,
  setList: (v: VideoCourtSchema[]) => void,
  setTotal: (v: number) => void
) {
  formRef.current?.resetFields()
  setCurrent(1)
  getTableData(null, formRef, current, pageSize, setLoading, setList, setTotal)
}

function tableChange (v: TablePaginationConfig, setCurrent: (v: number) => void, setPageSize: (v: number) => void) {
  const { current, pageSize } = v
  setCurrent(current || 1)
  setPageSize(pageSize || 10)
}

async function getResource (setResource: (v: {[k: string]: any}) => void) {
  const [e, d] = await awaitWrap(getResourceRequest())
  if (e === null && d !== null) {
    setResource(d)
  }
}

function renderResource (d: {[k: string]: any}) {
  return (
    <div className={style['resource-line']}>
      <Space size='large'>
        <span>存储空间总量：{d.sumCount || 0}GB</span>
        <span>已用存储空间：{d.usedRecStorage || 0}GB</span>
      </Space>
    </div>
  )
}

interface Props {
  title: string
}

function Main ({ title }: Props) {
  const formRef = useRef<FormInstance>(null)
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<VideoCourtSchema[]>([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [pagination, setPagination] = useState<TablePaginationConfig>()
  const [videoList, setVideoList] = useState<string[]>([])
  const [visible, setVisible] = useState(false)
  const [resource, setResource] = useState<{[k: string]: any}>({})
  function refreshFn (v = null) {
    getResource(setResource)
    getTableData(v, formRef, current, pageSize, setLoading, setList, setTotal)
  }
  useEffect(() => {
    setPagination({
      current,
      pageSize,
      total,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    })
    getResource(setResource)
    getTableData(null, formRef, current, pageSize, setLoading, setList, setTotal)
  }, [current, pageSize, total])
  useEffect(() => {
    getResource(setResource)
    getTableData(null, formRef, current, pageSize, setLoading, setList, setTotal)
  }, [])
  return (
    <div className={style.container}>
      <DetailModal visible={visible} data={videoList} hide={() => { setVideoList([]); setVisible(false) }} />
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <div className={style['search-container']}>
        <div className={style['search-form']}>
          <Form name='my_case_manage' {...layout} ref={formRef} onFinish={v => { setCurrent(1); refreshFn(v) }}>
            <Row gutter={24}>
              <Col span={8}>
                <Item label='案号/预约人员' name='searchKey' labelCol={{ flex: '120px' }}>
                  <Input placeholder='请输入' allowClear />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='开始日期' name='start_date'>
                  <DatePicker className={style.full} placeholder='请选择日期' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='结束日期' name='end_date'>
                  <DatePicker className={style.full} placeholder='请选择日期' />
                </Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={16} />
              <Col span={8}>
                <Item>
                  <div className={style['search-btns']}>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => resetHandle(formRef, current, pageSize, setCurrent, setLoading, setList, setTotal)}>重置
                    </Button>
                  </div>
                </Item>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className={style['table-btns-line']}>
        {renderResource(resource)}
      </div>
      <div className={style['table-container']}>
        <Table rowKey='uuID' loading={loading} columns={getColumns(refreshFn, setVideoList, setVisible)} dataSource={list} pagination={pagination} onChange={(v) => tableChange(v, setCurrent, setPageSize)} />
      </div>
    </div>
  )
}

export default Main
